#include "HttpServer.h"
#include "block_log.h"
#include "Log.h"
#include "../utils/cpp-httplib/httplib.h"
#include <chrono>
#include <thread>

HttpServer::HttpServer(const std::string& base_dir, int port)
    : m_baseDir(base_dir), m_port(port), m_running(false)
{
}

HttpServer::~HttpServer()
{
    stop();
}

bool HttpServer::start()
{
    if (m_running) {
        Debug("HTTP服务器已经在运行");
        return false;
    }
    
    // 启动服务器线程
    m_serverThread = std::thread(&HttpServer::serverThreadFunc, this);
    
    // 等待一小段时间确保服务器启动
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    
    return m_running;
}

void HttpServer::stop()
{
    if (m_running) {
        m_running = false;
        if (m_serverThread.joinable()) {
            m_serverThread.join();
        }
        Debug("HTTP服务器已停止");
    }
}

void HttpServer::serverThreadFunc()
{
    httplib::Server svr;
    
    Debug("HTTP服务器启动中，端口: %d, 根目录: %s", m_port, m_baseDir.c_str());
    
    // 设置静态文件目录
    // 访问 http://localhost:8080/uploads/avatars/xxx.jpg
    // 会映射到 ./uploads/avatars/xxx.jpg
    bool ret = svr.set_mount_point("/", m_baseDir.c_str());
    
    if (!ret) {
        Debug("HTTP服务器挂载目录失败: %s", m_baseDir.c_str());
        return;
    }
    
    // 设置CORS（跨域访问支持）
    svr.set_default_headers({
        {"Access-Control-Allow-Origin", "*"},
        {"Access-Control-Allow-Methods", "GET, OPTIONS"},
        {"Access-Control-Allow-Headers", "Content-Type"}
    });
    
    // OPTIONS请求处理（预检请求）
    svr.Options(".*", [](const httplib::Request&, httplib::Response& res) {
        res.status = 200;
    });
    
    // 添加日志中间件（注意：lambda需要捕获或使用静态函数）
    svr.set_logger([](const httplib::Request& req, const httplib::Response& res) {
        printf("[HTTP] %s %s - Status: %d\n", 
              req.method.c_str(), 
              req.path.c_str(), 
              res.status);
    });
    
    // 错误处理
    svr.set_error_handler([](const httplib::Request& req, httplib::Response& res) {
        std::string error_msg = "<html><body><h1>404 Not Found</h1><p>文件不存在: " 
                              + req.path + "</p></body></html>";
        res.set_content(error_msg, "text/html; charset=utf-8");
    });
    
    m_running = true;
    Debug("HTTP服务器启动成功，监听端口 %d", m_port);
    Debug("访问URL示例: http://localhost:%d/uploads/avatars/xxx.jpg", m_port);
    
    // 阻塞监听（在独立线程中运行）
    svr.listen("0.0.0.0", m_port);
    
    m_running = false;
}

